package com.wxy.selector.多线程优化;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author 47868
 */
public class Server {
    static class Worker implements Runnable {
        private Thread thread;
        private Selector selector;
        private String name;
        private volatile boolean flag = false;
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();
        public Worker(String name){
            this.name = name;
        }
        public void register(SocketChannel socketChannel) throws IOException {
            if(!flag){
                selector = Selector.open();
                thread = new Thread(this, name);
                thread.start();
                flag = true;
            }
            queue.add(()->{
                try {
                    socketChannel.register(selector,SelectionKey.OP_READ,null);
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            });
            selector.wakeup();  //selector阻塞 使用wakeup方法唤醒 继续执行下面代码
        }

        @Override
        public void run() {
            while (true){
                try {
                    selector.select();
                    Runnable task = queue.poll();
                    if(task != null){
                        task.run();
                    }
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        try {
                            if (key.isReadable()){
                                System.out.println("reading...");
                                SocketChannel socketChannel = (SocketChannel) key.channel();
                                ByteBuffer buffer = ByteBuffer.allocate(24);
                                int readed = socketChannel.read(buffer);
                                if(readed == -1){
                                    key.cancel();
                                    continue;
                                }
                                buffer.flip();
                                while (buffer.hasRemaining()){
                                    System.out.print((char) buffer.get());
                                }
                                System.out.println();
                                buffer.compact();
                                System.out.println("readed...");
                            }
                        }
                        catch (IOException e){
                            System.out.println(e.getMessage());
                            key.cancel();
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("Boss");
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8888));
        Selector selector = Selector.open();
        SelectionKey sscKey = serverSocketChannel.register(selector,0,null);
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        //创建固定数量的worker
        Worker worker = new Worker("worker-0");
        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()){
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    System.out.println("connected\t"+socketChannel);
                    //关联
                    worker.register(socketChannel);
                    System.out.println("registered");
                }
            }
        }
    }
}
